package com.donfu.web.controller.wxhouse;

import com.donfu.common.annotation.Log;
import com.donfu.common.core.controller.BaseController;
import com.donfu.common.core.domain.AjaxResult;
import com.donfu.common.core.page.TableDataInfo;
import com.donfu.common.enums.BusinessType;
import com.donfu.common.utils.poi.ExcelUtil;
import com.donfu.system.domain.house.*;
import com.donfu.system.service.house.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 评价信息Controller
 *
 * @author mo
 * @date 2021-12-01
 */
@Api(tags = "前台-客人之家")
@RestController
@RequestMapping("/wx/house/comment")
public class WebHouseCommentController extends BaseController {
    @Autowired
    private IHouseCommentService houseCommentService;
    @Autowired
    private IHouseCommentLikeService houseCommentLikeService;
    @Autowired
    private IHouseProductTypeService houseProductTypeService;
    @Autowired
    private IHouseCollectionService houseCollectionService;
    @Autowired
    private IHouseGoodsService houseGoodsService;
    @Autowired
    private IHouseOrderService houseOrderService;

    /**
     * 查询产品一级类型列表
     */
    @GetMapping("/proType")
    public AjaxResult productType() {
        List<Map<String, Object>> types = houseProductTypeService.selectHouseProductTypePName();
        return AjaxResult.success(types);
    }

    /**
     * 评论点赞
     */
//    @PreAuthorize("@ss.hasPermi('house:like:add')")
//    @Log(title = "评论点赞", businessType = BusinessType.INSERT)
    @PostMapping("/like")
    public AjaxResult add(@RequestBody HouseCommentLike houseCommentLike) {
        if (houseCommentLike != null && houseCommentLike.getUserId() != null) {
            if (houseCommentLike != null && houseCommentLike.getStatus() != null) {
                if (houseCommentLike.getStatus() == 0) {
                    //点赞
                    houseCommentLike.setStatus(1);
                    houseCommentLike.setCreateDate(new Date());
                    int result = houseCommentLikeService.insertHouseCommentLike(houseCommentLike);
                    //String key = "commentLike_" + houseCommentLike.getUserId();
                    if (result != 0) {
                        //存入redis
                        //redisTemplate.opsForValue().set(key, houseCommentLike);
                        //修改评论点赞数
                        HouseComment comment = houseCommentService.selectHouseCommentById(houseCommentLike.getCommentId().longValue());
                        if (comment != null && comment.getLikeNum() != null) {
                            HouseComment upComment = new HouseComment();
                            upComment.setLikeNum(comment.getLikeNum() + 1);
                            upComment.setId(comment.getId());
                            upComment.setUpdateDate(new Date());
                            int updateHouseComment = houseCommentService.updateHouseComment(upComment);
                            if (updateHouseComment == 1) {
                                return AjaxResult.success("点赞成功");
                            } else {
                                return AjaxResult.error("点赞失败");
                            }
                        }
                        return AjaxResult.error("评论为空");
                    }
                } else {
                    //取消点赞，获取点赞id 修改状态
                    HouseCommentLike like = new HouseCommentLike();
                    like.setStatus(houseCommentLike.getStatus());
                    like.setUserId(houseCommentLike.getUserId());
                    like.setCommentId(houseCommentLike.getCommentId());
                    List<HouseCommentLike> houseCommentLikes = houseCommentLikeService.selectHouseCommentLikeList(like);
                    if (houseCommentLikes.size() > 0) {
                        houseCommentLike.setId(houseCommentLikes.get(0).getId());
                        houseCommentLike.setStatus(0);
                        houseCommentLike.setUpdateDate(new Date());
                        int i = houseCommentLikeService.updateHouseCommentLike(houseCommentLike);
                        if (i != 0) {
                            //修改评论点赞数
                            HouseComment comment = houseCommentService.selectHouseCommentById(houseCommentLike.getCommentId().longValue());
                            if (comment != null && comment.getLikeNum() != null) {
                                HouseComment upComment = new HouseComment();
                                upComment.setLikeNum(comment.getLikeNum() - 1);
                                upComment.setId(comment.getId());
                                upComment.setUpdateDate(new Date());
                                int updateHouseComment = houseCommentService.updateHouseComment(upComment);
                                if (updateHouseComment == 1) {
                                    return AjaxResult.success("取消点赞成功");
                                }
                            }
                        } else {
                            return AjaxResult.error("取消点赞失败");
                        }
                    }
                }
            }
            return AjaxResult.error("点赞失败");
        }
        return AjaxResult.error("请先登录");
    }


    @PostMapping("/collection")
    public AjaxResult collection(@RequestBody HouseComment houseComment) {
        HouseCollection houseCollection = new HouseCollection();
        if (houseComment.getUserId() != null) {
            if (houseComment != null && houseComment.getCollStatus() != null && houseComment.getId() != null) {
                if (houseComment.getCollStatus() == 0) {
                    //收藏
                    houseCollection.setUserId(houseComment.getUserId());
                    houseCollection.setType(2);//\
                    // 类型 1产品 2客人之家 3新居日志
                    houseCollection.setValueId(houseComment.getId());
                    houseCollection.setCreateDate(new Date());
                    int result = houseCollectionService.insertHouseCollection(houseCollection);
                    if (result == 1) {
                        //存入redis
                        //redisTemplate.opsForValue().set(key, houseCommentLike);
                        //修改评论收藏数
                        HouseComment comment = houseCommentService.selectHouseCommentById(houseComment.getId().longValue());
                        if (comment != null && comment.getLikeNum() != null) {
                            HouseComment upComment = new HouseComment();
                            upComment.setCollecNum(comment.getCollecNum() + 1);
                            upComment.setId(comment.getId());
                            upComment.setUpdateDate(new Date());
                            int updateHouseComment = houseCommentService.updateHouseComment(upComment);
                            if (updateHouseComment == 1) {
                                return AjaxResult.success("收藏成功");
                            } else {
                                return AjaxResult.error("收藏失败");
                            }
                        }
                        return AjaxResult.error("评论为空");
                    }
                } else {
                    //取消收藏，获取收藏id
                    HouseCollection collection = new HouseCollection();
                    collection.setUserId(houseComment.getUserId());
                    collection.setType(2);//类型 1产品 2客人之家 3新居日志
                    collection.setValueId(houseComment.getId());
                    List<HouseCollection> houseCollections = houseCollectionService.selectHouseCollectionList(collection);
                    if (houseCollections.size() > 0) {
                        int i = houseCollectionService.deleteHouseCollectionById(houseCollections.get(0).getId());
                        if (i != 0) {
                            //修改评论收藏数
                            HouseComment comment = houseCommentService.selectHouseCommentById(houseCollections.get(0).getValueId().longValue());
                            if (comment != null && comment.getCollecNum() != null) {
                                HouseComment upComment = new HouseComment();
                                upComment.setCollecNum(comment.getCollecNum() - 1);
                                upComment.setId(comment.getId());
                                upComment.setUpdateDate(new Date());
                                int updateHouseComment = houseCommentService.updateHouseComment(upComment);
                                if (updateHouseComment == 1) {
                                    return AjaxResult.success("取消收藏成功");
                                }
                            }
                        } else {
                            return AjaxResult.error("取消收藏失败");
                        }
                    }
                }
            }
            return AjaxResult.error("收藏失败");
        }
        return AjaxResult.error("请先登录");
    }

    /**
     * 查询客人之家列表
     */
//    @PreAuthorize("@ss.hasPermi('house:comment:list')")
    @GetMapping("/list")
    public TableDataInfo list(Integer userId,String productName) {
        startPage();
        if (userId != null) {
            HouseComment houseComment = new HouseComment();
            houseComment.setStandby(productName);
            List<HouseComment> list = houseCommentService.selectHouseEvaluateList(houseComment);
            for (HouseComment comment : list) {
                if (comment != null) {
                    //查询评价顶级商品类型
                    if (comment.getGoodsId() != null) {
                        //查询评价的商品详情
                        HouseGoods houseGoods = houseGoodsService.selectHouseGoodsById(comment.getGoodsId().longValue());
                        if (houseGoods != null && houseGoods.getProducyTypeId() != null) {
                            //查询评价的商品顶级类型
                            HouseProductType houseProductType = houseProductTypeService.selectHouseProductTypeById(houseGoods.getProducyTypeId());
                            if (houseProductType != null && houseProductType.getPid() != null && houseProductType.getPid() != 0) {
                                //二级查询评价的商品顶级类型
                                HouseProductType productType = houseProductTypeService.selectHouseProductTypeById(houseProductType.getPid());
                                comment.setProductName(productType.getProductName());
                                //类型存进数据库
                                HouseComment Comment = new HouseComment();
                                Comment.setId(comment.getId());
                                Comment.setStandby(productType.getProductName());
                                houseCommentService.updateHouseComment(Comment);
                            } else {
                                comment.setProductName(houseProductType.getProductName());
                                //类型存进数据库
                                HouseComment Comment = new HouseComment();
                                Comment.setId(comment.getId());
                                Comment.setStandby(houseProductType.getProductName());
                                houseCommentService.updateHouseComment(Comment);
                            }
                        }
                    }
                    //根据用户di查询收藏列表
                    HouseCollection houseCollection = new HouseCollection();
                    houseCollection.setType(2);// 1产品 2兰影展 3新居日志
                    houseCollection.setValueId(comment.getId());
                    houseCollection.setUserId(new Long(userId));
                    List<HouseCollection> houseCollections = houseCollectionService.selectHouseCollectionList(houseCollection);
                    if (houseCollections.size() > 0) {
                        //该用户已收藏
                        comment.setCollStatus(new Long(1));
                    } else {
                        //该用户未收藏
                        comment.setCollStatus(new Long(0));
                    }
                    //根据用户id查询点赞表
                    HouseCommentLike houseCommentLike = new HouseCommentLike();
                    houseCommentLike.setUserId(userId);
                    houseCommentLike.setCommentId(comment.getId().intValue());
                    List<HouseCommentLike> houseCommentLikes = houseCommentLikeService.selectHouseCommentLikeList(houseCommentLike);
                    if (houseCommentLikes.size() > 0) {
                        //该用户已点赞
                        comment.setLikeStatus(new Long(1));
                    } else {
                        //该用户未点赞
                        comment.setLikeStatus(new Long(0));
                    }
                }
            }
            return getDataTable(list);
        }
        return null;
    }

    /**
     * 获取评价信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('house:comment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id, Integer userId) {
        HouseComment houseComment = houseCommentService.selectHouseCommentById(id);
        if (userId != null) {
            if (houseComment != null) {
                //评价下面的评论
                HouseComment c = new HouseComment();
                List<HouseComment> houseComments = houseCommentService.selectHouseCommentList(c);
                List<HouseComment> parents = new ArrayList<>();
                for (HouseComment comment : houseComments) {
                    //根据用户id查询点赞表
                    HouseCommentLike houseCommentLike = new HouseCommentLike();
                    houseCommentLike.setUserId(userId);
                    houseCommentLike.setCommentId(comment.getId().intValue());
                    houseCommentLike.setStatus(1);
                    List<HouseCommentLike> houseCommentLikes = houseCommentLikeService.selectHouseCommentLikeList(houseCommentLike);
                    if (houseCommentLikes.size() > 0) {
                        //该用户已点赞
                        comment.setLikeStatus(new Long(1));
                    } else {
                        //该用户未点赞
                        comment.setLikeStatus(new Long(0));
                    }
                    if (comment.getParentId() != null) {
                        //存放二级评论
                        if (comment.getParentId() == houseComment.getId().intValue()) {
                            parents.add(comment);
                        }
                    }
                }
                //子评论
                for (HouseComment parent : parents) {
                    for (HouseComment comment : houseComments) {
                        if (comment.getParentId() != null) {
                            if (comment.getParentId() == parent.getId().intValue()) {
                                if (parent.getChildren() == null) {
                                    parent.setChildren(new ArrayList<>());
                                }
                                //把三级评论存到二级评论
                                parent.getChildren().add(comment);
                            }
                        }
                    }
                }
                houseComment.setChildren(parents);

                //根据用户di查询收藏列表
                HouseCollection houseCollection = new HouseCollection();
                houseCollection.setType(2);// 1产品 2兰影展 3新居日志
                houseCollection.setValueId(houseComment.getId());
                houseCollection.setUserId(new Long(userId));
                List<HouseCollection> houseCollections = houseCollectionService.selectHouseCollectionList(houseCollection);
                if (houseCollections.size() > 0) {
                    //该用户已收藏
                    houseComment.setCollStatus(new Long(1));
                } else {
                    //该用户未收藏
                    houseComment.setCollStatus(new Long(0));
                }
                //根据用户id查询点赞表
                HouseCommentLike houseCommentLike = new HouseCommentLike();
                houseCommentLike.setUserId(userId);
                houseCommentLike.setCommentId(houseComment.getId().intValue());
                houseCommentLike.setStatus(1);
                List<HouseCommentLike> houseCommentLikes = houseCommentLikeService.selectHouseCommentLikeList(houseCommentLike);
                if (houseCommentLikes.size() > 0) {
                    //该用户已点赞
                    houseComment.setLikeStatus(new Long(1));
                } else {
                    //该用户未点赞
                    houseComment.setLikeStatus(new Long(0));
                }
            }
            return AjaxResult.success(houseComment);
        }
        return AjaxResult.error("请先登录");
    }

    //商品评论
    @GetMapping("/comments")
    public TableDataInfo list(HouseComment houseComment) {
        startPage();
        if (houseComment!=null&&houseComment.getGoodsId()!=null&&houseComment.getUserId()!=null) {
            HouseComment com = new HouseComment();
            com.setGoodsId(houseComment.getGoodsId());
            List<HouseComment> houseComments = houseCommentService.selectHouseCommentList(com);
       /* for (int i = 0; i < houseComments.size(); i++) {
            //评论信息存入redis
            redisTemplate.opsForValue().set("comment:" + houseComments.get(i).getId(), houseComments.get(i));
        }*/
            //二级评论
            if (houseComments == null || houseComments.size() == 0) {
                return null;
            }
            List<HouseComment> parents = new ArrayList<>();
            List<HouseComment> tows = new ArrayList<>();
            for (HouseComment comment : houseComments) {
                //根据用户id查询点赞表
                HouseCommentLike houseCommentLike = new HouseCommentLike();
                houseCommentLike.setUserId(houseComment.getUserId().intValue());
                houseCommentLike.setCommentId(comment.getId().intValue());
                houseCommentLike.setStatus(1);
                List<HouseCommentLike> houseCommentLikes = houseCommentLikeService.selectHouseCommentLikeList(houseCommentLike);
                if (houseCommentLikes.size() > 0) {
                    //该用户已点赞
                    comment.setLikeStatus(new Long(1));
                } else {
                    //该用户未点赞
                    comment.setLikeStatus(new Long(0));
                }
                if (comment.getParentId() == null) {
                    //一级评论集合
                    parents.add(comment);
                }
            }
            // 遍历一级评论集合
            for (HouseComment parent : parents) {
                // 拿到所有评论, 然后与一级评论相比较， 拿到所有一级评论的子评论
                for (HouseComment comment : houseComments) {
                    if (comment.getParentId() != null) {
                        if (comment.getParentId() == parent.getId().intValue()) {
                            if (parent.getChildren() == null) {
                                parent.setChildren(new ArrayList<>());
                            }
                            // 将二级存入一级子集
                            parent.getChildren().add(comment);
                            tows.add(comment);
                        }
                    }

                }
            }
            for (HouseComment tow : tows) {
                // 拿到所有评论, 然后与二级评论相比较， 拿到所有二级评论的子评论
                for (HouseComment comment : houseComments) {
                    if (comment.getParentId() != null) {
                        if (comment.getParentId() == tow.getId().intValue()) {
                            if (tow.getChildren() == null) {
                                tow.setChildren(new ArrayList<>());
                            }
                            // 将三级存入二级子集
                            tow.getChildren().add(comment);
                        }
                    }

                }
            }
            return getDataTable(parents);
        }
        TableDataInfo dataTable = getDataTable(null);
        dataTable.setCode(500);
        dataTable.setMsg("参数错误");
        return dataTable;
    }


    /**
     * 新增评价信息
     */
//    @PreAuthorize("@ss.hasPermi('house:comment:add')")
//    @Log(title = "评价信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HouseComment houseComment, @RequestParam Integer orderId) {
        if (orderId!=null) {
            houseComment.setCreateDate(new Date());
            /* houseComment.setLikeStatus(new Long(0));
            houseComment.setCollStatus(new Long(0));*/
            int i = houseCommentService.insertHouseComment(houseComment);
            if (i==1){
                //修改订单状态
                HouseOrder order = new HouseOrder();
                order.setId(new Long(orderId));
                order.setOrderStatus(5);//订单状态 1待付款 2待发货 3待收货 4待评价 5已完成
                int houseOrder = houseOrderService.updateHouseOrder(order);
                if (houseOrder==1) {
                    return AjaxResult.success("评价成功");
                }
            }
            return AjaxResult.error("新增失败");
        }
      return AjaxResult.error("参数错误");
    }



    @PostMapping("/add")
    public AjaxResult addComment(@RequestBody HouseComment houseComment) {
        if (houseComment!=null&&houseComment.getUserId()!=null) {
            houseComment.setCreateDate(new Date());
            /* houseComment.setLikeStatus(new Long(0));
            houseComment.setCollStatus(new Long(0));*/
            int i = houseCommentService.insertHouseComment(houseComment);
            if (i==1){
                    return AjaxResult.success("评论成功");
                }
            return AjaxResult.error("评论失败");
            }
        return AjaxResult.error("参数错误");
    }
}
